<?php
namespace App\Http\Controllers\Wxxcx;

use App\Services\Wxxcx\UserService;
use App\Utilitys\Upload;
use Illuminate\Http\Request;
use App\Utilitys\Wxxcx;

class AuthController extends BaseController
{
    //小程序授权

    protected $app_id = 'wx2812bb4a4a3795a2';
    protected $app_secret = 'caece3b032255b47ebd64500a9806ab9';

    public function __construct(UserService $wxxcxDB)
    {
        $this->service = $wxxcxDB;
    }

    /**
     * 授权
     */
    public function auth(Request $request)
    {
        $wxcode = $request->post('wxcode', '');
        $pas['h5code'] = $request->post('h5code', '');
        $pas['userInfo'] = $request->post('userInfo', '');
        $pas['nickName'] = $request->post('nickName', '');
        $pas['avatarUrl'] = $request->post('avatarUrl', '');
        if (!$pas['nickName'] || !$pas['avatarUrl']) {
            return $this->toJson(-2, '微信昵称或头像必须的');
        }
        if (substr($pas['avatarUrl'], 0, 5) == 'data:') {
            $uhead = Upload::getPathByBase64($pas['avatarUrl']);
            $pas['avatarUrl'] = env('DOMAIN').'/'.$uhead;
        }
        if (!$wxcode) {
            return $this->toJson(-2, '微信CODE必须的');
        }
        $resWx = $this->wxtoken($wxcode);
        if ($resWx['code'] < 0) {
            return $this->toJson(-2, $resWx['msg']);
        }
        $pas['openid'] = $resWx['data'];
        $res = $this->service->auth($pas);
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson(0, '', $res['data']);
    }

    /**
     * 用户详细授权，access_token
     */
    public function wxtoken($code)
    {
        //GET（请使用https协议） https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
        $appid = $this->app_id; //env('WECHAT_APPID');
        $appsecret = $this->app_secret; //env('WECHAT_SECRET');
        if ($code == '0000') {
            $openid = $code;
        } else {
            $httpUrl = 'https://api.weixin.qq.com/sns/jscode2session';
            $httpUrl .= '?appid=' . $appid;
            $httpUrl .= '&secret=' . $appsecret;
            $httpUrl .= '&js_code=' . $code;
            $httpUrl .= '&grant_type=authorization_code';
            $resCurl = $this->wxCurl($httpUrl);
            if ($resCurl['code'] < 0) {
                return ['code' => -2, 'msg' => $resCurl['msg']];
            }
            $openid = $resCurl['data']['openid'];
        }
        return ['code' => 0, 'msg' => 'success', 'data' => $openid];
    }

    /**
     * 构建CURL请求，单线程
     * @param $url 请求地址
     * @param $string 参数拼接的字符串
     * @param $method 请求方式：put、post、get、delete
     * @return $json
     */
    public function wxCurl($url)
    {
        $curl = curl_init(); //初始化
        curl_setopt($curl,CURLOPT_URL,$url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_TIMEOUT, 5);
        $output = curl_exec($curl);
        curl_close($curl);
        if (!$output) {
            return array('code'=>-1, 'msg'=>'请求失败');
        }
        $items = json_decode($output,true);
        return array('code' => 0, 'msg' => 'success', 'data' => $items);
    }

    /**
     * 微信审核
     */
    public function wxauth(Request $request)
    {
        $config = 'config.json';
        $configs = file_get_contents($config);
        $configs = json_decode($configs, true);
        if (isset($configs['xcx']['iswx'])) {
            $wx = $configs['xcx']['iswx'];
        } else {
            $wx = 0;
        }
        return $this->toJson(0, '', ['iswx' => $wx]);
    }
}